<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>今日订单</span>
              <el-tag size="small" type="success">实时</el-tag>
            </div>
          </template>
          <div class="stat-value">{{ stats.todayOrders }}</div>
          <div class="stat-label">较昨日 {{ stats.orderChange > 0 ? '+' : ''}}{{ stats.orderChange }}%</div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>营业额</span>
              <el-tag size="small" type="warning">今日</el-tag>
            </div>
          </template>
          <div class="stat-value">¥{{ stats.todayRevenue }}</div>
          <div class="stat-label">较昨日 {{ stats.revenueChange > 0 ? '+' : ''}}{{ stats.revenueChange }}%</div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>活跃用户</span>
              <el-tag size="small" type="info">今日</el-tag>
            </div>
          </template>
          <div class="stat-value">{{ stats.activeUsers }}</div>
          <div class="stat-label">较昨日 {{ stats.userChange > 0 ? '+' : ''}}{{ stats.userChange }}%</div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>热门菜品</span>
              <el-tag size="small" type="danger">TOP</el-tag>
            </div>
          </template>
          <div class="stat-value">{{ stats.hotDish }}</div>
          <div class="stat-label">已售 {{ stats.hotDishOrders }} 份</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>营业趋势</span>
              <el-radio-group v-model="chartTimeRange" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <!-- 这里需要集成图表库，如 ECharts -->
            <div ref="revenueChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>分类销量占比</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="categoryChart" style="height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新订单 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>最新订单</span>
          <el-button type="text" @click="$router.push('/admin/orders')">
            查看全部
          </el-button>
        </div>
      </template>
      
      <el-table :data="latestOrders" style="width: 100%">
        <el-table-column prop="order_number" label="订单号" width="180" />
        <el-table-column prop="created_at" label="下单时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="user.username" label="用户" />
        <el-table-column prop="total_amount" label="金额">
          <template #default="scope">
            ¥{{ scope.row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

const store = useStore()
const chartTimeRange = ref('week')
const revenueChart = ref<HTMLElement | null>(null)
const categoryChart = ref<HTMLElement | null>(null)

interface DashboardStats {
  todayOrders: number
  orderChange: number
  todayRevenue: number
  revenueChange: number
  activeUsers: number
  userChange: number
  hotDish: string
  hotDishOrders: number
}

const stats = ref<DashboardStats>({
  todayOrders: 0,
  orderChange: 0,
  todayRevenue: 0,
  revenueChange: 0,
  activeUsers: 0,
  userChange: 0,
  hotDish: '',
  hotDishOrders: 0
})

const latestOrders = ref([])

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '待支付': 'warning',
    '已支付': 'success',
    '已完成': 'success',
    '已取消': 'info'
  }
  return statusMap[status] || 'info'
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/admin/dashboard', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      stats.value = data.stats
      latestOrders.value = data.latest_orders
      initCharts(data.chart_data)
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

// 初始化图表
const initCharts = (chartData: any) => {
  // 收入趋势图
  if (revenueChart.value) {
    const chart = echarts.init(revenueChart.value)
    chart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: chartData.revenue.dates
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: chartData.revenue.values,
        type: 'line',
        smooth: true,
        areaStyle: {}
      }]
    })
  }

  // 分类占比图
  if (categoryChart.value) {
    const chart = echarts.init(categoryChart.value)
    chart.setOption({
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: '70%',
        data: chartData.category_sales
      }]
    })
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-card {
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin: 10px 0;
  }
  
  .stat-label {
    font-size: 14px;
    color: #909399;
  }
}

.chart-container {
  margin-top: 20px;
}
</style> 